package com.wuchu.shiro.shiro;


import com.wuchu.shiro.pojo.User;
import com.wuchu.shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 类描述：
 * Author: WuChu
 * Date: 2022/3/3
 * Version: 1.0
 */
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;


    /**
     * 提供授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了==>AuthorizationInfo");
        SimpleAuthorizationInfo  simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        //获取当前认证用户
        Subject subject = SecurityUtils.getSubject();
        //强制转换成User
        User user = (User) subject.getPrincipal();
        //获取用户的权限
        String perm = user.getPerms();
        System.out.println(user);
        //给当前用户授权
        simpleAuthorizationInfo.addStringPermission(perm);

        return simpleAuthorizationInfo;
    }


    /**
     * 提供认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了==>AuthenticationInfo");

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        //只需判断用户名，密码shiro自动帮你认证(不能泄露)
        User user = userService.queryByName(usernamePasswordToken.getUsername());

        if(user == null) {
            return null;
        }
        /**
         * 返回三个参数：
         * 1、一个principal(主角),当前认证用户，可以在授权中获取该用户
         * 2、当前用户的password
         * 3、realmName
         */


        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
